package com.codeZ.FlyweightPattern.example;

import java.util.HashMap;
import java.util.Map;

/**
 * 享元工厂类
 *
 * @author codeZhang
 * @Date 2024/8/16 09:22
 */
public class FlyweightFactory {

    private static final Map<String,Flyweight> pool = new HashMap<>();

    static {
        pool.put("A",new ConcreteFlyweight("A"));
        pool.put("B",new ConcreteFlyweight("B"));
        pool.put("C",new ConcreteFlyweight("C"));
        pool.put("D",new ConcreteFlyweight("D"));
        pool.put("E",new ConcreteFlyweight("E"));
    }

    public static Flyweight getFlyweight(String key) {
        //对象存在,从享元池直接返回
        if(pool.containsKey(key)){
            System.out.println("===享元池中存在,直接复用,key:" + key);
            return pool.get(key);

        }else{
            //如果对象不存在,先创建一个新的对象添加到享元池中,然后返回
            System.out.println("===享元池中不存在,创建并复用,key:" + key);
            Flyweight fw = new ConcreteFlyweight(key);
            pool.put(key,fw);
            return fw;
        }
    }


}
